var blockly3 = {
		initBlockly:function(){
			//可变Blockly
			Blockly.Blocks['var'] = {
			  init: function() {
				var method = [["ref", "ref"], ["cross", "cross"], ["last", "last"], ["barslast", "barslast"], ["mema", "mema"], ["history_min", "history_min"]];
				var dropdown = new Blockly.FieldDropdown(method,function(option){
					 var divisorInput = option;
				     this.sourceBlock_.updateShape_(divisorInput);
				});
			    this.appendValueInput("param1")
			        .setCheck(null)
			        .appendField("self.")
			        .appendField(dropdown,"method")
			        .appendField("(");
			    this.appendValueInput("param2")
			        .setCheck(null)
			        .appendField(",");
			    this.appendValueInput("param3")
			        .setCheck(null)
			        .appendField(",");
			    this.appendDummyInput("dummyInput")
			        .appendField(")");
			    this.setTooltip('');
			    this.setColour(100);
			    this.setHelpUrl('http://www.example.com/');
			  },
			  updateShape_: function(divisorInput) {
				  this.setOutput(true, null);
				  this.removeInput("dummyInput");
				  var param4 = this.getInput("param4");
				  var param3 = this.getInput("param3");
				  var param2 = this.getInput("param2");
				  if(!param2){
					  this.appendValueInput("param2")
				  	  .setCheck(null)
				  	  .appendField(","); 
				  }
				  if(!param3){
					  this.appendValueInput("param3")
				  	  .setCheck(null)
				  	  .appendField(","); 
				  }
				  if(divisorInput=='cross' || divisorInput=='last'){
					  if(!param4){
						  this.appendValueInput("param4")
						  	  .setCheck(null)
						  	  .appendField(",");
					  }
				  }else if(divisorInput=='history_min'){
					  this.removeInput("param2");
					  this.removeInput("param3");
					  this.removeInput("param4")
				  }else if(divisorInput=='barslast' || divisorInput=='mema'){
					  this.removeInput("param3");
					  this.removeInput("param4")
				  }else{
					  this.setOutput(false, null);
					  this.removeInput("param4")
				  }
				  this.appendDummyInput("dummyInput")
			  	  .appendField(")");
			  }
			};
			Blockly.Python['var'] = function(block) {
			  var paramArr = [];
			  var dropdown_name = block.getFieldValue('method');
			  var value_param1 = Blockly.Python.valueToCode(block, 'param1', Blockly.Python.ORDER_ATOMIC);
			  var value_param2 = Blockly.Python.valueToCode(block, 'param2', Blockly.Python.ORDER_ATOMIC);
			  var value_param3 = Blockly.Python.valueToCode(block, 'param3', Blockly.Python.ORDER_ATOMIC);
			  var value_param4 = Blockly.Python.valueToCode(block, 'param4', Blockly.Python.ORDER_ATOMIC);
			  if(value_param1){paramArr.push(value_param1)};
			  if(value_param2){paramArr.push(value_param2)};
			  if(value_param3){paramArr.push(value_param3)};
			  if(value_param4){paramArr.push(value_param4)};
			  var param = paramArr.join(",");
			  var code = "self.ref("+param+")";
			  return [code, Blockly.Python.ORDER_NONE];
			  
			};
			//初始化地区
			var PROVINCE;
			$.ajax({
				url:"addSCPRedis",
				datatype:"json",
				type:"GET",
				async:false,
				success:function(data){
					PROVINCE = data;
				}
			});
			var regions = [];
			var provinces = [];
			var first;
			var i = 0;
			for(var key in PROVINCE){
				provinces.push([key,key]);
				if(i==0){
					var map = PROVINCE[key];
					for (var i=0;i<map.length;i++){
						first = map[0];
						regions.push([map[i],map[i]]);
					}
				}
				i++;
			}
			
			Blockly.Blocks['region'] = {
			  init: function() {
				  var dropdown = new Blockly.FieldDropdown(provinces,function(option){
						 var divisorInput = option;
					     this.sourceBlock_.updateShape_(divisorInput);
					});
				  var regionDropdown = new Blockly.FieldDropdown(regions,function(option){
						 var divisorInput = option;
					     this.sourceBlock_.updateShape_(divisorInput);
					});
			    this.appendDummyInput("regionINP")
			    	.appendField(dropdown, "PROVINCE")
			        .appendField(regionDropdown, "REGION");
			    this.setColour(180);
			    this.setTooltip('');
			    this.setHelpUrl('http://www.example.com/');
			    this.setPreviousStatement(true, "type");
			    this.setNextStatement(true, "type");
			  },
			  updateShape_: function(divisorInput) {
				 var region = this.getFieldValue("REGION");
				 var regions = [];
				 var set = PROVINCE[divisorInput];
				 if(set!=undefined){
					 for (var i=0;i<set.length;i++){
						 var map = set[i];
						 if(map!=null){
							 regions.push([map,map]);
						 }
					 }
					 var input = this.getInput("regionINP");
					 input.removeField("REGION");
					 var regionDropdown = new Blockly.FieldDropdown(regions,function(option){
						 var divisorInput = option;
					     this.sourceBlock_.updateShape_(divisorInput);
					});
					 input.appendField(regionDropdown,"REGION");
					 divisorInput = set[0];
				 }
				 //下拉改变地区的行业
				 blockly3.initGICS_INDU(divisorInput);
			  }
			};
			Blockly.Python['region'] = function(block) {
			  var dropdown_region = block.getFieldValue('REGION');
			  var code = dropdown_region;
			  return "region:"+code+",";
			};
			//行业Blockly
			blockly3.initGICS_INDU(first);
			Blockly.Python['gics_indu'] = function(block) {
			  var dropdown_GICS_IND = block.getFieldValue('GICS_IND');
			  var code = dropdown_GICS_IND;
			  return "gics_ind:"+code+",";
			};
			
			//财务
				Blockly.Blocks['finance'] = {
					  init: function() {
						this.setColour(100);
					    this.appendValueInput("caiwu")
					        .setCheck(['tablename'])
					        .appendField("财务");
					    this.appendValueInput("fanwei")
				        .setCheck(['tablename'])
				        .appendField("范围");
					    this.setPreviousStatement(true, "type");
					    this.setNextStatement(true, "type");
					    this.setHelpUrl('http://www.example.com/');
					    this.setTooltip('');
					  }
				};
				Blockly.Python["finance"]=function a(a) {
					var caiwu = Blockly.Python.valueToCode(a, 'caiwu');
					var fanwei = Blockly.Python.valueToCode(a, 'fanwei');
					var code = "CW("+caiwu+")CW"+fanwei;
					return [code];
				};
				Blockly.Blocks['scope'] = {
				  init: function() {
					 this.setColour(1);
				    this.appendDummyInput()
				        .appendField("最小值")
				        .appendField(new Blockly.FieldNumber(0, 0, Infinity, 10), "min")
				        .appendField("最大值")
				        .appendField(new Blockly.FieldNumber(60000, 0, Infinity, 10), "max");
				    this.setOutput(true,null);
				    this.setTooltip('');
				    this.setHelpUrl('http://www.example.com/');
				  }
				};
				Blockly.Python['scope'] = function(block) {
				  var text_min = block.getFieldValue('min');
				  var text_max = block.getFieldValue('max');
				  return ["min:"+text_min+",max:"+text_max+","];
				};
				//策略
				Blockly.Blocks['strategy'] = {
						  init: function() {
						    this.appendStatementInput("strategy")
						        .setCheck(['strategy'])
						        .appendField("策略");
						    this.setPreviousStatement(true, "type");
						    this.setNextStatement(true, "type");
						    this.setHelpUrl('http://www.example.com/');
						    this.setTooltip('');
						  }
				};
				Blockly.Python["strategy"]=function a(a) {
					var c = Blockly.Python.statementToCode(a, 'strategy');
					return "CL("+c+")CL";
				};
				Blockly.Blocks['dkbf'] = {
				  init: function() {
				    this.appendDummyInput()
				        .appendField("DKBF");
				    this.setPreviousStatement(true, "strategy");
				    this.setNextStatement(true,"strategy");
				    this.setTooltip('');
				    this.setHelpUrl('http://www.example.com/');
				  }
				};
				Blockly.Python['dkbf'] = function(block) {
				  return 'DKBF,';
				};
				Blockly.Blocks['hsb'] = {
				  init: function() {
				    this.appendDummyInput()
				        .appendField("HSB");
				    this.setPreviousStatement(true, "strategy");
				    this.setNextStatement(true,"strategy");
				    this.setTooltip('');
				    this.setHelpUrl('http://www.example.com/');
				  }
				};
				Blockly.Python['hsb'] = function(block) {
				  return 'HSB,';
				}; 
				Blockly.Blocks['frcs'] = {
				  init: function() {
				    this.appendDummyInput()
				        .appendField("FRCS");
				    this.setPreviousStatement(true, "strategy");
				    this.setNextStatement(true,"strategy");
				    this.setTooltip('');
				    this.setHelpUrl('http://www.example.com/');
				  }
				};
				Blockly.Python['frcs'] = function(block) {
				  return 'FRCS,';
				}; 
				Blockly.Blocks['macd'] = {
				  init: function() {
				    this.appendDummyInput()
				        .appendField("MACD");
				    this.setPreviousStatement(true, "strategy");
				    this.setNextStatement(true,"strategy");
				    this.setTooltip('');
				    this.setHelpUrl('http://www.example.com/');
				  }
				};
				Blockly.Python['macd'] = function(block) {
				  return 'MACD,';
				};
				Blockly.Blocks['desc'] = {
				  init: function() {
					this.setColour(270);
				    this.appendDummyInput()
				        .appendField("DESC");
				    this.setPreviousStatement(true, "tablename");
				    this.setNextStatement(true,"tablename");
				    this.setTooltip('');
				    this.setHelpUrl('http://www.example.com/');
				  }
				};
				Blockly.Python['desc'] = function(block) {
				  return 'DESC,';
				};
				Blockly.Blocks['asc'] = {
				  init: function() {
					this.setColour(220);
				    this.appendDummyInput()
				        .appendField("ASC");
				    this.setPreviousStatement(true, "tablename");
				    this.setNextStatement(true,"tablename");
				    this.setTooltip('');
				    this.setHelpUrl('http://www.example.com/');
				  }
				};
				Blockly.Python['asc'] = function(block) {
				  return 'ASC,';
				};
				var strategyCategory = document.getElementById("strategy");
				var strategy = [];
				
				strategy.push("<block type='strategy'></block>");
				var addStrategy = function(name){
					strategy.push("<block type='"+name+"'></block>");
					Blockly.Blocks[name] = {
					  init: function() {
						this.setColour(220);
					    this.appendDummyInput()
					        .appendField(name);
					    this.setPreviousStatement(true, "tablename");
					    this.setNextStatement(true,"tablename");
					    this.setTooltip('');
					    this.setHelpUrl('http://www.example.com/');
					  }
					};
				}
				//从reids中拿策略
				$.ajax({
					url:"findRedisStrategy",
					async:false,
					success:function(data){
						for(var i=0;i<data.length;i++){
							var name = data[i];
							addStrategy(name);
						}
					}
				});
				
				
				strategy.push("<block type='macd' id='macd'></block>");
				strategy.push("<block type='dkbf' id='dkbf'></block>");
				strategy.push("<block type='frcs' id='frcs'></block>");
				strategy.push("<block type='hsb' id='hsb'></block>");
				strategyCategory.innerHTML = strategy.join("");
			
		},
		/**
		 * 获取行业和地区相交的股票
		 * @param code
		 */
		interStockcode:function(code){
			var param = blockly3.strToJson("{"+str+"}");
			$.ajax({
				type:"post",
				datatype:"json",
				url:"interSTOCKCODE",
				data:param,
				success:function(data){
					alert(data);
				}
			})
		},
		/**
		 * 初始化行业
		 * @param first
		 */
		initGICS_INDU:function(first){
			$.ajax({
				url:"initGICS_INDU",
				datatype:"json",
				data:{"city":first},
				type:"GET",
				async:false,
				success:function(data){
					var gics_indu = [];
					for(var i=0;i<data.length;i++){
						var map = data[i];
						gics_indu.push([map["GICS_INDU_NAME"],map["GICS_INDU_CODE"]]);
					}
					Blockly.Blocks['gics_indu'] = {
					  init: function() {
					    this.appendDummyInput()
					        .appendField(new Blockly.FieldDropdown(gics_indu), "GICS_IND");
					    this.setPreviousStatement(true, "type");
					    this.setNextStatement(true,"type");
					    this.setTooltip('');
					    this.setColour(100);
					    this.setHelpUrl('http://www.example.com/');
					  }
					};
				}
			});
		},
		/**
		 * json转换为字符串
		 * @param str
		 * @returns
		 */
		strToJson:function(str){ 
			var json = eval('(' + str + ')'); 
			return json; 
		},
		/**
		 * 初始化表选项
		 */
		initTablesBlockly:function(){
			var stock = [];
			var stockCategory = document.getElementById("stock");
			var addTable = function(tablename,fields){
				Blockly.Blocks[tablename] = {
					init: function(){
						this.setColour(1);
						this.appendDummyInput()
							.appendField(tablename,"TABLE")//new Blockly.FieldDropdown([[item.name,name]])
							.appendField(new Blockly.FieldDropdown(fields), "FIELD");
						this.setOutput(true,null);
						this.setTooltip('');
						this.setHelpUrl('http://www.example.com/');
					}
				};
				Blockly.Python[tablename] = function(block){
					var table = block.getFieldValue("TABLE");
					var field = block.getFieldValue("FIELD");
					var str = "SS."+table+"."+field+"";
					return [str];
				}
			};
			$.ajax({
				url:"initTables",
				datatype:"json",
				async:false,
				success:function(data){
					for(var key in data){
						var fields = [];
						var set = data[key];
						for(var i=0;i<set.length;i++){
							var field = set[i].substring(key.length+4)
							fields.push([field,field]);
						}
						addTable(key,fields);
						stock.push("<block type='"+key+"'></block>")
					}
				}
			});
			
			Blockly.Blocks['operation'] = {
			  init: function() {
			    this.appendValueInput("first")
			        .setCheck(null);
			    this.appendDummyInput()
			        .appendField(new Blockly.FieldDropdown([["+", "+"], ["-", "-"], ["×", "*"], ["÷", "/"]]), "operator");
			    this.appendValueInput("last")
			        .setCheck(null);
			    this.setOutput(true, null);
			    this.setColour(100);
			    this.setTooltip('');
			    this.setHelpUrl('http://www.example.com/');
			  }
			};
			Blockly.Python['operation'] = function(block) {
			  var value_first = Blockly.Python.valueToCode(block, 'first', Blockly.Python.ORDER_ATOMIC);
			  var dropdown_operator = block.getFieldValue('operator');
			  var value_last = Blockly.Python.valueToCode(block, 'last', Blockly.Python.ORDER_ATOMIC);
			  var code = value_first+dropdown_operator+value_last;
			  return [code, Blockly.Python.ORDER_NONE];
			};
			Blockly.Blocks['cxg'] = {
			  init: function() {
			    this.appendDummyInput()
			        .appendField("次新股");
			    this.setPreviousStatement(true, null);
			    this.setNextStatement(true, null);
			    this.setColour(200);
			    this.setTooltip('');
			    this.setHelpUrl('http://www.example.com/');
			  }
			};
			Blockly.Python['cxg'] = function(block) {
			  var code = 'CXG,';
			  return code;
			};
			stock.push("<block type='cxg'></block>");
			stock.push("<block type='operation'></block>");
			stock.push("<block type='finance'></block>");
			/*stock.push("<block type='desc' id='DESC'></block>")
			stock.push("<block type='asc' id='ASC'></block>")*/
			stock.push("<block type='scope' id='scope'></block>")
			stock.push("<block type='region'></block>")
			stock.push("<block type='gics_indu'></block>")
			stockCategory.innerHTML=stock.join("");
		},operation:function(code){
			$.get("operation",{"param":code},function(data){
				console.log(data);
				alert(data);
			})
		}
}

